<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>日志文件管理器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#6B7280',
                        warning: '#F59E0B',
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .breadcrumb-item:not(:last-child)::after {
                content: "/";
                margin: 0 8px;
                color: #9CA3AF;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <header class="mb-8">
            <h1 class="text-2xl font-bold text-gray-800 mb-2">
                <i class="fa fa-folder-open text-primary mr-2"></i>日志文件管理器
            </h1>
            <p class="text-gray-600">浏览日志目录并下载所需文件</p>
        </header>

        <!-- 导航区域 -->
        <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <!-- 面包屑导航 -->
                <div class="flex flex-wrap items-center text-sm">
                    <span class="breadcrumb-item">
                        <button id="rootDirBtn" class="text-primary hover:underline flex items-center">
                            <i class="fa fa-home mr-1"></i>根目录
                        </button>
                    </span>
                    <div id="breadcrumbContainer"></div>
                </div>
                
                <!-- 导航控制 -->
                <div class="flex gap-2">
                    <button id="backBtn" class="bg-gray-200 hover:bg-gray-300 px-3 py-1 rounded flex items-center disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                        <i class="fa fa-arrow-left mr-1"></i>上一级
                    </button>
                    <button id="refreshBtn" class="bg-gray-200 hover:bg-gray-300 px-3 py-1 rounded flex items-center">
                        <i class="fa fa-refresh mr-1"></i>刷新
                    </button>
                </div>
            </div>
            
            <!-- 搜索框 -->
            <div class="mt-4 relative">
                <input 
                    type="text" 
                    id="searchInput" 
                    placeholder="搜索文件夹或文件..." 
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50"
                >
                <i class="fa fa-search absolute right-3 top-3 text-gray-400"></i>
            </div>
        </div>

        <!-- 目录内容区域 -->
        <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <div class="p-4 bg-primary text-white">
                <h2 class="font-semibold text-lg">
                    <i class="fa fa-list mr-2"></i>目录内容
                    <span id="itemCount" class="ml-2 text-sm bg-white/20 px-2 py-0.5 rounded-full">0 项</span>
                </h2>
            </div>
            
            <div id="directoryContent" class="p-4 max-h-[calc(100vh-220px)] overflow-y-auto">
                <!-- 加载状态 -->
                <div class="flex justify-center p-12 text-gray-500">
                    <i class="fa fa-circle-o-notch fa-spin mr-2"></i>加载中...
                </div>
            </div>
        </div>
    </div>

    <script>
        // API基础地址，根据实际情况修改
        const API_BASE_URL = 'https://localhost:7081/api/logs';
        
        // 导航状态
        let currentPath = '';          // 当前路径（相对于日志根目录）
        let pathHistory = [];          // 浏览历史
        let historyIndex = -1;         // 当前历史索引
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 加载根目录内容
            loadDirectoryContent('');
            
            // 绑定事件
            document.getElementById('backBtn').addEventListener('click', goBack);
            document.getElementById('refreshBtn').addEventListener('click', refreshCurrentDirectory);
            document.getElementById('rootDirBtn').addEventListener('click', () => navigateTo(''));
            document.getElementById('searchInput').addEventListener('input', filterItems);
        });
        
        /**
         * 加载指定路径的目录内容
         */
        async function loadDirectoryContent(path) {
            const contentContainer = document.getElementById('directoryContent');
            
            // 显示加载状态
            contentContainer.innerHTML = `
                <div class="flex justify-center p-12 text-gray-500">
                    <i class="fa fa-circle-o-notch fa-spin mr-2"></i>加载中...
                </div>
            `;
            
            try {
                // 请求目录内容
                const response = await fetch(`${API_BASE_URL}/directory?path=${encodeURIComponent(path)}`);
                
                if (!response.ok) {
                    throw new Error(`加载失败 (${response.status})`);
                }
                
                const data = await response.json();
                
                if (!data || !Array.isArray(data.items)) {
                    throw new Error('数据格式不正确');
                }
                
                // 更新当前路径
                currentPath = path;
                
                // 更新历史记录
                updateHistory(path);
                
                // 渲染目录内容
                renderDirectoryContent(data.items);
                
                // 更新面包屑
                updateBreadcrumb(path);
                
                // 更新导航按钮状态
                updateNavigationButtons();
                
            } catch (error) {
                contentContainer.innerHTML = `
                    <div class="p-8 text-center text-red-500">
                        <i class="fa fa-exclamation-circle mr-2"></i>${error.message || '加载目录失败'}
                    </div>
                `;
                console.error('加载目录失败:', error);
            }
        }
        
        /**
         * 渲染目录内容
         */
        function renderDirectoryContent(items) {
            const contentContainer = document.getElementById('directoryContent');
            const itemCountElement = document.getElementById('itemCount');
            
            // 更新项目计数
            itemCountElement.textContent = `${items.length} 项`;
            
            if (items.length === 0) {
                contentContainer.innerHTML = `
                    <div class="p-8 text-center text-gray-500">
                        <i class="fa fa-info-circle mr-2"></i>该目录下没有内容
                    </div>
                `;
                return;
            }
            
            let html = '<div class="space-y-1">';
            
            // 先渲染文件夹，再渲染文件
            const directories = items.filter(item => item.isDirectory);
            const files = items.filter(item => !item.isDirectory);
            
            // 渲染文件夹
            directories.forEach(dir => {
                html += `
                    <div class="directory-item">
                        <button 
                            class="w-full text-left px-4 py-3 rounded hover:bg-gray-100 transition flex items-center"
                            data-name="${escapeHtml(dir.name)}"
                        >
                            <i class="fa fa-folder text-warning mr-3 text-lg"></i>
                            <span>${escapeHtml(dir.name)}</span>
                        </button>
                    </div>
                `;
            });
            
            // 渲染文件
            files.forEach(file => {
                // 格式化文件大小和修改时间
                const fileSize = file.fileSizeDisplay || formatFileSize(file.fileSize || 0);
                const lastWriteTime = file.lastWriteTime 
                    ? new Date(file.lastWriteTime).toLocaleString() 
                    : '未知时间';
                
                html += `
                    <div class="file-item">
                        <div class="flex items-center justify-between px-4 py-3 rounded hover:bg-gray-100 transition">
                            <div class="flex items-center">
                                <i class="fa fa-file-text-o text-primary mr-3 text-lg"></i>
                                <span class="truncate max-w-[300px]">${escapeHtml(file.name)}</span>
                            </div>
                            <div class="flex items-center gap-4">
                                <span class="text-sm text-gray-500 hidden sm:inline-block">${fileSize}</span>
                                <span class="text-sm text-gray-500 hidden md:inline-block">${lastWriteTime}</span>
                                <a 
                                    href="${API_BASE_URL}/download?dir=${encodeURIComponent(currentPath)}&file=${encodeURIComponent(file.name)}"
                                    class="text-primary hover:text-primary/80 transition"
                                    title="下载文件"
                                >
                                    <i class="fa fa-download"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            contentContainer.innerHTML = html;
            
            // 绑定文件夹点击事件（进入子目录）
            document.querySelectorAll('.directory-item button').forEach(btn => {
                btn.addEventListener('click', () => {
                    const dirName = btn.getAttribute('data-name');
                    // 构建新路径
                    const newPath = currentPath 
                        ? `${currentPath}/${dirName}` 
                        : dirName;
                    
                    navigateTo(newPath);
                });
            });
        }
        
        /**
         * 导航到指定路径
         */
        function navigateTo(path) {
            loadDirectoryContent(path);
        }
        
        /**
         * 返回上一级目录
         */
        function goBack() {
            if (historyIndex > 0) {
                historyIndex--;
                const previousPath = pathHistory[historyIndex];
                loadDirectoryContent(previousPath);
            }
        }
        
        /**
         * 刷新当前目录
         */
        function refreshCurrentDirectory() {
            loadDirectoryContent(currentPath);
        }
        
        /**
         * 更新历史记录
         */
        function updateHistory(path) {
            // 清除当前索引后的历史
            if (historyIndex < pathHistory.length - 1) {
                pathHistory = pathHistory.slice(0, historyIndex + 1);
            }
            
            // 添加新路径（如果不同）
            if (pathHistory.length === 0 || pathHistory[pathHistory.length - 1] !== path) {
                pathHistory.push(path);
                historyIndex = pathHistory.length - 1;
            }
        }
        
        /**
         * 更新面包屑导航
         */
        function updateBreadcrumb(path) {
            const breadcrumbContainer = document.getElementById('breadcrumbContainer');
            breadcrumbContainer.innerHTML = '';
            
            if (!path) {
                return; // 根目录没有额外面包屑
            }
            
            // 拆分路径为各个部分
            const pathParts = path.split('/').filter(part => part);
            let currentSubPath = '';
            
            pathParts.forEach((part, index) => {
                currentSubPath = currentSubPath 
                    ? `${currentSubPath}/${part}` 
                    : part;
                
                const breadcrumbItem = document.createElement('span');
                breadcrumbItem.className = 'breadcrumb-item';
                
                // 最后一部分只是文本
                if (index === pathParts.length - 1) {
                    breadcrumbItem.innerHTML = `<span class="text-gray-700">${escapeHtml(part)}</span>`;
                } else {
                    // 前面的部分可点击
                    const btn = document.createElement('button');
                    btn.className = 'text-primary hover:underline';
                    btn.textContent = part;
                    btn.addEventListener('click', () => navigateTo(currentSubPath));
                    breadcrumbItem.appendChild(btn);
                }
                
                breadcrumbContainer.appendChild(breadcrumbItem);
            });
        }
        
        /**
         * 更新导航按钮状态
         */
        function updateNavigationButtons() {
            document.getElementById('backBtn').disabled = historyIndex <= 0;
        }
        
        /**
         * 过滤目录项
         */
        function filterItems() {
            const filterText = (document.getElementById('searchInput').value || '').toLowerCase();
            const dirItems = document.querySelectorAll('.directory-item');
            const fileItems = document.querySelectorAll('.file-item');
            
            let hasVisibleItems = false;
            
            // 过滤文件夹
            dirItems.forEach(item => {
                const dirName = item.querySelector('button').getAttribute('data-name').toLowerCase();
                const isVisible = dirName.includes(filterText);
                item.style.display = isVisible ? '' : 'none';
                if (isVisible) hasVisibleItems = true;
            });
            
            // 过滤文件
            fileItems.forEach(item => {
                const fileName = item.querySelector('span').textContent.toLowerCase();
                const isVisible = fileName.includes(filterText);
                item.style.display = isVisible ? '' : 'none';
                if (isVisible) hasVisibleItems = true;
            });
        }
        
        /**
         * 格式化文件大小
         */
        function formatFileSize(bytes) {
            if (typeof bytes !== 'number' || isNaN(bytes) || bytes < 0) {
                return '0 B';
            }
            
            if (bytes < 1024) return `${bytes} B`;
            if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
            if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
            return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
        }
        
        /**
         * HTML转义
         */
        function escapeHtml(unsafe) {
            if (typeof unsafe !== 'string') return '';
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }
    </script>
</body>
</html>
    